package com.hrx.controller;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller()
@RequestMapping("/ordersController")
public class OrdersController {
	@Autowired
    private RedisTemplate<String, Object>  redisTemplate;
	public static final String SUCCESS = "success";
	public static final String FAIL = "fail";
	
	
	@ResponseBody
	@RequestMapping("/insert")
	public String insert(String key,String value){
		try{
			System.out.println(key+"---------------"+value);
			redisTemplate.opsForValue().set(key, value,60*10,TimeUnit.SECONDS);
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	@ResponseBody
	@RequestMapping("/find")
	public String find(String key){
		try{
			String value = (String) redisTemplate.opsForValue().get(key);
			System.out.println(key+":"+value);
			return value;
		}catch(Exception e){
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public String delete(String key){
		try{
			redisTemplate.delete(key);
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	@ResponseBody
	@RequestMapping("/update")
	public String update(String key,String value){
		try{
			if(find(key) != null){
				redisTemplate.opsForValue().set(key, value,60*10,TimeUnit.SECONDS);
				return SUCCESS;
			}
			else
				return FAIL;
		}catch(Exception e){
			e.printStackTrace();
			return e.getMessage();
		}
	}
}
